<template>
	<div class="answer_questionsList_container">
		<div class="condition">
			<span>展开层级</span>
			<el-select style="width: 1.8rem;" v-model="curLevel" placeholder="请选择">
				<el-option v-for="item in levelOptions" :key="item.value" 
					:label="item.label" :value="item.value">
				</el-option>
			</el-select>
			&nbsp;
			  
			<el-input style="width: 3.5rem;" placeholder="搜索 题目名称" clearable
   				 		  v-model="keyWords" class="input_search" maxlength="100">
  			</el-input>
  			&nbsp;
  			<div class="search_btn" @click="search()">搜索</div>
			
			
			<div class="center_btn" @click="publishQuestion($event)" 
				v-if="hasApi('questionPublish')"  v-show="published!=null">
				{{published==1?'取消发布':'发布到校区'}}
			</div>
			<div class="left_btn" @click="openQuestionAdd()" v-if="hasApi('questionAddEdit')">
				新建题目
			</div>
		</div>
		<!--     <div class="questionTree">
      <el-tree ref="questionTree"  :data="questionList" :load="loadNodeData" :default-expand-all="isExpandAll" :props="defaultProps" node-key="childrenId" @node-expand="handleNodeExpand" :filter-node-method="filterNode">
        <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="tree_front">
          <span :class="treeLevelClass[node.level-1]" :title="node.label">{{ node.label }}</span>
        <div v-if="data.hasFileFlag" class="downfile-div"></div>
        </span>
        <span v-if="node.level != 1 &&node.level != 5">
          <div class="tree_icon_edit" @click.stop="() => openQuestionAddEdit(node, data)"></div>
          <span class="tree_operate" @click.stop="() => openQuestionAddEdit(node, data)">编辑</span>
        <div class="tree_icon_delete" @click.stop="() => removeQuestion(node, data)"></div>
        <span class="tree_operate" @click.stop="() => removeQuestion(node, data)">删除</span>
        </span>
        </span>
      </el-tree>
    </div>
  </div> -->
		<div class="questionTree">
			<el-tree ref="questionTree" :data="questionList" :load="loadNodeData" :default-expand-all="isExpandAll" :props="defaultProps" node-key="childrenId" @node-expand="handleNodeExpand" :filter-node-method="filterNode">
				<span class="custom-tree-node" slot-scope="{ node, data }">
        <!-- <span><i :class="node.icon"></i>{{ node.label }}</span> -->
				<span class="tree_front">
			        <span :class="treeLevelClass[node.level-1]" :title="node.label">{{ node.label }}</span>
					<div v-if="(data.isHasFile && data.extDesc=='') || (node.level==5 && data.isHasFile) " class="downfile-div"></div>
				</span>
				<!--阶段-->
				<span v-if="node.level == 1">
					<template v-if="hasApi('questionAddEdit')">
			        	<div class="tree_icon_edit" @click.stop="() => openPeriodAddEdit(data)"></div>
			        	<span class="tree_operate" @click.stop="() => openPeriodAddEdit(data)">编辑</span>
			        </template>	
			        <template v-if="hasApi('questionDelete')">
						<!--<div class="tree_icon_delete" @click.stop="() => removeQuestion(node, data)"></div>
						<span class="tree_operate" @click.stop="() => removeQuestion(node, data)">删除</span>-->
				        <div class="tree_icon_delete" style="visibility: hidden;"></div>
						<span class="tree_operate" style="visibility: hidden;">删除</span>
					</template>
				</span>
				<!--题目-->
				<span v-else-if="node.level != 5">
					<template v-if="hasApi('questionAddEdit')">
			        	<div class="tree_icon_edit" @click.stop="() => openQuestionEdit(node, data)"></div>
			        	<span class="tree_operate" @click.stop="() => openQuestionEdit(node, data)">编辑</span>
			        </template>
			        <template v-if="hasApi('questionDelete')">
						<div class="tree_icon_delete" @click.stop="() => removeQuestion(node, data)"></div>
						<span class="tree_operate" @click.stop="() => removeQuestion(node, data)">删除</span>
					</template>
				</span>
				</span>
			</el-tree>
		</div>
	</div>
</template>
<script>
	var vm, user;
	export default {
		components: {},
		data: function() {
			return {
				keyWords: "",
				curLevel: 0,
				isExpandAll: false,
				loadData: true, //控制数据是不是继续加载
				treeLevelClass: ["tree_level_1", "tree_level_2", "tree_level_3", "tree_level_4", "tree_level_5"],
				levelOptions: [{
					value: 0,
					label: "全部"
				}, {
					value: 1,
					label: "一级"
				}, {
					value: 2,
					label: "二级"
				}, {
					value: 3,
					label: "三级"
				}, {
					value: 4,
					label: "四级"
				}],
				questionList: [],
				childrenList: [],
				defaultProps: {
					children: "data",
					label: 'childrenName', // 这里的名字要和你封装的数据中的节点的名字一样
					isLeaf: 'leaf'
				},
				published: null,
				evaTypeId: null
			}
		},
		compute: {

		},
		methods: {
			openQuestionAdd: function() { //新增题目
				var param = {
					evaTypeId: vm.evaTypeId
				}
				this.$emit('openQuestionAddEdit', param);
			},
			openQuestionEdit: function(node, data) { //编辑题目
				var param = {
					evaTypeId: vm.evaTypeId,
					level: node.level - 1,
					childrenId: data.childrenId,
					childrenName: data.childrenName,
					extDesc: data.extDesc,
					isHasFile: data.isHasFile,
					hasFileUrl: data.hasFileUrl,
					periodOptionId: "",
					firstQuestionOptionId: "",
					secondQuestionOptionId: "",
				}
				switch(node.level) {
					case 1:
						break;
					case 2:
						param.periodOptionId = node.parent.data.childrenId;
						break;
					case 3:
						param.firstQuestionOptionId = node.parent.data.childrenId;
						param.periodOptionId = node.parent.parent.data.childrenId;
						break;
					case 4:
						param.secondQuestionOptionId = node.parent.data.childrenId;
						param.firstQuestionOptionId = node.parent.parent.data.childrenId;
						param.periodOptionId = node.parent.parent.parent.data.childrenId;
						break;
					case 5:
						break;
				}
				this.$emit('openQuestionAddEdit', param);
			},
			openPeriodAddEdit: function(data) { //编辑阶段
				let param = {
					evaTypeId: vm.evaTypeId,
					level : 1,
					parentId : 0,
					titleId : (data? data.childrenId : undefined),
					titleName : (data? data.childrenName : ""),
					createUserId : user.userId
				}
				this.$emit('openPeriodAddEdit', param);
			},
			removeQuestion : function(node, data) {
				const parent = node.parent;
				const children = parent.data.childNodes || parent.childNodes;
				const index = children.findIndex(d => d.data.childrenId === data.childrenId);

				let message = "将删除该题目及其该题目下的子题目，确定删除吗？";
				if(node.level == 1) {
					message = "将删除该阶段及其所有题目，确定删除吗？";
				}

				if(node.childNodes && node.childNodes.length > 0) {
					vm.$confirm(message, '删除', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						api.questionDelete({ titleId: data.childrenId }).then(function(data) {
							children.splice(index, 1);

							vm.$message({
								type: 'success',
								message: '删除成功!'
							});
						});

					});
				} else {
					api.questionDelete({
						titleId: data.childrenId
					}).then(function(data) {
						children.splice(index, 1);
						vm.$message({
							type: 'success',
							message: '删除成功!'
						});
					});
				}

			},
			search: function() {
				vm.$refs.questionTree.filter(vm.keyWords);
				vm.curLevelChange();
			},
			filterNode: function(value, data) {
				if(!value) return true;
				return data.childrenName.indexOf(value) !== -1;
			},
			curLevelChange: function() {
				switch(vm.curLevel) {
					case 0:
						// vm.isExpandAll = true;
						for(var i = 0; i < vm.$refs.questionTree.store._getAllNodes().length; i++) {
							vm.$refs.questionTree.store._getAllNodes()[i].expanded = true;
						}
						break;
					case 1:
						for(var i = 0; i < vm.$refs.questionTree.store._getAllNodes().length; i++) {
							if(vm.$refs.questionTree.store._getAllNodes()[i].level <= 1)
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = true;
							else
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = false;
						}
						break;
					case 2:
						for(var i = 0; i < vm.$refs.questionTree.store._getAllNodes().length; i++) {
							if(vm.$refs.questionTree.store._getAllNodes()[i].level <= 2)
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = true;
							else
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = false;
						}
						break;
					case 3:
						for(var i = 0; i < vm.$refs.questionTree.store._getAllNodes().length; i++) {
							if(vm.$refs.questionTree.store._getAllNodes()[i].level <= 3)
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = true;
							else
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = false;
						}
						break;
					case 4:
						for(var i = 0; i < vm.$refs.questionTree.store._getAllNodes().length; i++) {
							if(vm.$refs.questionTree.store._getAllNodes()[i].level <= 4)
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = true;
							else
								vm.$refs.questionTree.store._getAllNodes()[i].expanded = false;
						}
						break;
					default:
						vm.isExpandAll = false;
						break;
				}
			},
			handleNodeExpand: function(node) {
				// console.log(data);
			},
			loadNodeData: function(node, resolve) {
				if(vm.loadData) {
					if(node.level === 0) {
						vm.node = node;
						vm.resolve = resolve;

						// if(vm.questionList.length>0)
						return resolve(vm.questionList);
						// else return
					}
					if(node.level > 4) return resolve([]);
					//获取子节点数据
					vm.getChildrenNode(node, resolve);
				}

			},
			getChildrenNode: function(node, resolve) {
				api.questionChild({
					parentId: node.data.childrenId,
					evaTypeId: vm.evaTypeId
				}).then(function(data) {
					node.data.data = node.data.data || data.list;
					// vm.childrenList = data;
					if(node.data.data.length == 0) {
						// vm.$message.info('没有下级数据！');
						node.isLeaf = true;
						node.loading = false;
						return;
					}
					var extChild = [];
					//重组数据
					for(var i = 0; i < node.data.data.length; i++) {
						if(node.data.data[i].hasFileUrl) {
							if(node.data.data[i].extDesc && node.data.data[i].extDesc != "") {
								//描述及附件添加一个节点 
								node.data.data[i].data = [];
								node.data.data[i].data.push({
									hasFileUrl: node.data.data[i].hasFileUrl,
									isHasFile: true,
									level: 5,
									extDesc: "",
									childrenId: node.data.data[i].childrenId + "_",
									childrenName: node.data.data[i].extDesc,
									leaf: true,
								});
							} else {
								node.data.data[i].isHasFile = true;
							}
						}
					}

					resolve(node.data.data);
				}).catch(function(error) {
					vm.$message.error(node.data.childrenName + '数据拉取失败，请刷新再试！');
					node.loading = false;
					if(node.level === 5) {
						node.isLeaf = true;
					}
				});
			},
			getAllData: function() { //一次性获取所有数据
				api.questionAllChild({
					parentId: -1,
					orgId: user.orgId
				}).then(function(data) {
					//保存数据
					vm.questionList = data.list;
					vm.evaTypeId = data.evaTypeId;

					vm.$nextTick(function() {
						vm.curLevel = 1;
						vm.curLevelChange();
					});
				});
				//检查是否有发布
				api.questionCheckPublish({
					orgId: user.orgId
				}).then(function(data) {
					vm.published = data.published;
				});

			},
			publishQuestion: function(e) {
				//按钮不会自动失去焦点，坑!
				$(e.currentTarget).blur();
				let param = {
					orgId: user.orgId,
					evaTypeId: vm.evaTypeId,
					published: (vm.published == 1 ? 0 : 1)
				};
				api.questionPublish(param).then(function(data) {
					vm.published = param.published;
					let message = (vm.published == 1 ? "发布成功" : "取消发布成功");
					tool.message({
						message: message,
						type: "success",
						showClose: true
					});
				})
			}
		},
		mounted: function() {
			vm.getAllData();
		},
		created: function() {
			vm = this;
			user = tool.getItem(lsKey.user, true);
		},
		beforeDestroy: function() {
			vm.loadData = false;
		}
	}
</script>
<style lang="scss">
	.answer_questionsList_container {
		.el-tree-node__content {
			height: 0.5rem;
			background-color: #f7f9fc;
		}
		.el-tree-node__children .el-tree-node__content {
			background-color: white;
		}
		.el-tree-node:focus>.el-tree-node__content {
			background-color: #d1e3ff;
		}
		.el-tree-node__content:hover {
			background-color: #e4efff;
		}
	}
</style>
<style scoped>
	.answer_questionsList_container {
		background-color: white;
		border: 0.01rem solid #ededed;
		border-radius: 0.1rem;
		padding: 0 0.3rem 0.4rem 0.3rem;
		color: #666666;
/*		height: 7.8rem;*/
	}
	
	.condition {
		padding: 0.2rem 0 0.3rem 0;
		font-size: 0.16rem;
		color: #666666;
	}
	
	
	
	.questionTree {
		max-height: calc(100% - 1rem);
		overflow: auto;
		/*display: none;*/
	}
	
	.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 0.16rem;
		padding-right: 0.08rem;
		/*line-height: 1rem;*/
	}
	
	.tree_front {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}
	
	.tree_level_1,
	.tree_level_2,
	.tree_level_3,
	.tree_level_4,
	.tree_level_5 {
		/*max-width: 80%;*/
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	
	.tree_level_1 {
		font-size: 0.24rem;
		color: #333333;
		max-width: 12.5rem;
	}
	
	.tree_level_2 {
		font-size: 0.22rem;
		color: #333333;
		max-width: 12.2rem;
	}
	
	.tree_level_3 {
		font-size: 0.2rem;
		color: #333333;
		max-width: 12rem;
	}
	
	.tree_level_4 {
		font-size: 0.18rem;
		color: #333333;
		max-width: 10.5rem;
	}
	
	.tree_level_5 {
		font-size: 0.16rem;
		max-width: 10.5rem;
	}
	
	.tree_icon_edit {
		display: inline-block;
		position: relative;
		width: 0.18rem;
		height: 0.18rem;
		background-image: url(../../../assets/img/answer_system/edit_icon.png);
		background-size: 100% 100%;
		margin: 0 auto;
		top: 0.03rem;
	}
	
	.tree_icon_delete {
		display: inline-block;
		position: relative;
		width: 0.18rem;
		height: 0.18rem;
		background-image: url(../../../assets/img/answer_system/delete_icon.png);
		background-size: 100% 100%;
		top: 0.03rem;
		margin-left: 0.2rem;
	}
	
	.tree_operate {
		font-size: 0.16rem;
		color: #666666;
	}
	
	.downfile-div {
		display: inline-block;
		width: 0.22rem;
		height: 0.17rem;
		margin-left: 0.5rem;
		background-image: url(../../../assets/img/answer_system/down_icon.png);
		background-repeat: no-repeat;
		background-position: center center;
		background-size: 100% 100%;
		/*padding-right: 0.4rem;*/
		letter-spacing: 0rem;
	}
	
	.page {
		text-align: right;
		padding-top: 0.1rem;
	}
</style>